package com.self.cloudmall.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.self.cloudmall.common.constant.EsConstant;
import com.self.cloudmall.common.dto.ElasticSkuDto;
import com.self.cloudmall.common.utils.R;
import com.self.cloudmall.search.config.ElasticConfig;
import com.self.cloudmall.search.service.ProductSearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class ProductSearchServiceImpl implements ProductSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public R productAdd(List<ElasticSkuDto> skuDtoList) throws IOException {
        //批量保存
        BulkRequest bulkRequest = new BulkRequest(EsConstant.PRODUCT_INDEX);
        for(ElasticSkuDto skuDto : skuDtoList){
            IndexRequest request = new IndexRequest();
            request.id(skuDto.getSkuId().toString());
            request.source(JSONObject.toJSONString(skuDto), XContentType.JSON);
            bulkRequest.add(request);
        }

        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, ElasticConfig.COMMON_OPTIONS);
        if (bulkResponse.hasFailures()){
            List<String> collect = Lists.newArrayList();
            for (BulkItemResponse item : bulkResponse.getItems()){
                if (item.isFailed()){
                    collect.add(item.getId());
                }
            }
            log.error("es保存数据部分失败，失败数据skuIds={}",collect);
            return R.error("es保存数据部分失败");
        }
        return R.ok();
    }
}
